package com.gz.moreaseManager.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gz.moreaseManager.core.exception.BizExceptionEnum;
import com.gz.moreaseManager.core.exception.ServiceException;
import com.gz.moreaseManager.sys.entity.Role;
import com.gz.moreaseManager.sys.entity.User;
import com.gz.moreaseManager.sys.mapper.UserMapper;
import com.gz.moreaseManager.sys.service.IUserRoleService;
import com.gz.moreaseManager.sys.service.IUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gz.moreaseManager.sys.transfer.SysUserVo;
import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author wike
 * @since 2019-02-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private IUserRoleService userRoleService;



    public Page<User> findUserListByParams(Page<User> page, EntityWrapper<User> wrapper){
        wrapper.isWhere(true);
        List<User> userList = userMapper.findPageByParams(page,wrapper);
        return page.setRecords(userList);
    }

    public User findOneByUserName(String userName) {
        if (UtilTool.isBlank(userName)) return null;

        User query = new User();
        query.setUserName( userName );
        User result = userMapper.selectOne(query);
        return result;
    }

    @Override
    public SysUserVo findUserByUserName(String userName) {
        if (UtilTool.isBlank(userName)) return null;

        SysUserVo sysUserVo = new SysUserVo();
        User query = new User();
        query.setUserName( userName );
        User result = userMapper.selectOne(query);
        //复制属性
        BeanUtils.copyProperties(result,sysUserVo);
        //获取角色列表
        setRoleInfo(sysUserVo);
        return sysUserVo;
    }

    @Override
    public SysUserVo findUserInfoByUserId(Integer userId) {
        if (UtilTool.isBlank(userId)) return null;
        SysUserVo sysUserVo = new SysUserVo();
        User user = userMapper.selectById(userId);
        //复制属性
        BeanUtils.copyProperties(user,sysUserVo);
        //获取角色列表
        setRoleInfo(sysUserVo);
        return sysUserVo;
    }

    @Override
    public boolean deleteUser(Integer userId) {
        if (UtilTool.isBlank(userId)) return false;
        return userMapper.deleteById(userId)==1;
    }

    @Override
    @Transactional
    public boolean addUserInfo(SysUserVo sysUserInfo) {
        if (UtilTool.isNotBlank(sysUserInfo.getUserName())
                && UtilTool.isNotBlank(sysUserInfo.getUserPhone())) {
            User user = new User();
            BeanUtils.copyProperties(sysUserInfo,user);
            //默认密码为111111
            user.setPassword(DigestUtils.md5Hex("88888888"));
            user.setUserAlias( sysUserInfo.getUserName() );//默认名称
            user.setCreateTime(new Date());

            //新增用户
            userMapper.insert(user);

            User queryUser = findOneByUserName(user.getUserName());
            //新增用户角色关联关系
            userRoleService.insertBatchByUserId(queryUser.getUserId(),sysUserInfo.getRoleIds());

        }
        return true;
    }

    @Override
    @Transactional
    public boolean updateUserInfo(SysUserVo sysUserInfo) {
        if (UtilTool.isNotBlank(sysUserInfo.getUserName())
                && UtilTool.isNotBlank(sysUserInfo.getUserPhone())) {


            User user = new User();
            BeanUtils.copyProperties(sysUserInfo,user);
            user.setUpdateTime(new Date());
            //对面密码-密码有做修改就加密处理
            if( UtilTool.isNotBlank(user.getPassword())){
                User oldUser = userMapper.selectById( sysUserInfo.getUserId() );
                if( !oldUser.getPassword().equals(user.getPassword()) ){
                    user.setPassword(DigestUtils.md5Hex(user.getPassword()));
                }
            }
            //修改用户
            userMapper.updateById( user);
            //新增用户角色关联关系
            userRoleService.insertBatchByUserId(sysUserInfo.getUserId(),sysUserInfo.getRoleIds());
        }
        return true;
    }

    /**
     * 根据状态修改用户
     *
     * @param status  状态
     * @param userIds 用户ID
     * @return 操作结果
     */
    private boolean updateUserInfoByUserIds(Byte status, Integer... userIds) {
        Map<String, Object> paramst = new HashMap<>();
        paramst.put("userIds", userIds);
        paramst.put("status", status);
        paramst.put("updateTime", new Date());
        int rows = userMapper.updateUserStatusBatchById( paramst );
        return true;
    }

    @Override
    public boolean enableUserBatch(Integer... userIds) {
        if (userIds == null)
            return false;
        return updateUserInfoByUserIds((byte) 1, userIds);
    }

    @Override
    public boolean disableUserBatch(Integer... userIds) {
        if (userIds == null)
            return false;
        return updateUserInfoByUserIds((byte) 2, userIds);
    }

    @Override
    public boolean resetPassword(String userName, String userPhone, String oldPass, String newPass) {
        //1.用户账号与手机号码验证是否存在当前用户
        User queryVo = new User();
        queryVo.setUserName( userName );
        User sysUserInfo = userMapper.selectOne( queryVo );
        if( sysUserInfo == null )
            throw new ServiceException(BizExceptionEnum.USER_NOT_EXISTED);
        if( UtilTool.isNotBlank( sysUserInfo.getUserPhone() )
                && !userPhone.equals(sysUserInfo.getUserPhone() ))
            throw new ServiceException(BizExceptionEnum.USER_PHONE_DIFFER);

        //2.旧密码是否一致
        String md5OldPass = DigestUtils.md5Hex(oldPass);
        if( UtilTool.isNotBlank( sysUserInfo.getPassword() )
                && !md5OldPass.equals( sysUserInfo.getPassword()))
            throw  new ServiceException(BizExceptionEnum.USER_PASSWORD_DIFFER);
        //3.修改为当前新密码
        String newPassWord = DigestUtils.md5Hex(newPass);
        sysUserInfo.setPassword( newPassWord );

        return userMapper.updateById(sysUserInfo)==1;
    }

    /**
     * 封装角色列表
     * @param sysUserVo
     * @return
     */
    public SysUserVo setRoleInfo(SysUserVo sysUserVo){
        List<Role> roleList = userRoleService.findRoleListByUserId(sysUserVo.getUserId());
        if( UtilTool.isNotBlank( roleList )){
            Integer size = roleList.size();
            Integer [] roleIds = new Integer[size];
            String [] roleNames = new String[size];
            for( int i=0;i<size;i++){
                roleIds[i]= roleList.get(i).getRoleId();
                roleNames[i] = roleList.get(i).getRoleName();
            }
            sysUserVo.setRoleIds(roleIds);
            sysUserVo.setRoleNames(roleNames);
        }
        return sysUserVo;
    }
}
